<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Turf - count</title>
  <style>
    #mapDiv { width: 800px; height: 440px; }
    .map-box{ padding: 10px; }
  </style>

  <script src="js/jquery-1.11.3.min.js"></script>
  <script src="js/turf.min.js"></script>
  <script src="https://maps.googleapis.com/maps/api/js?libraries=drawing"></script>
</head>
<body onload="initMap()">
  <div id="mapDiv"></div>


<script>
var map, infoWindow = new google.maps.InfoWindow({ content: "" });

function initMap() {
  // 地圖初始設定
  var mapOptions = {
      center: new google.maps.LatLng(25.07824, 121.54876),
      zoom: 11,
      mapTypeId: google.maps.MapTypeId.ROADMAP
  };

  var mapElement = document.getElementById("mapDiv");

  // Google 地圖初始化
  map = new google.maps.Map(mapElement, mapOptions);

  map.data.loadGeoJson('taipei.json', {}, function(features){
    for (var i = 0; i < features.length; i++) {

      features[i].toGeoJson(function(data){
        features[i].setProperty('turf_area', turf.area(data));
      });
    }
  });

  map.data.addListener('mouseover', function(e) {
    if( e.feature.getProperty('PTNAME') ){
      map.data.setStyle(function(feature){
        if( e.feature.getProperty('PTNAME') === feature.getProperty('PTNAME') ){
          return { fillOpacity: 0.55, fillColor: '#2EB0A9', strokeWeight: 2, strokeColor: '#333', strokeOpacity: 1 };
        }
      });
    }
  });

  map.data.addListener('mouseout', function(e) { map.data.revertStyle(); });

  map.data.addListener('click', function(e) {
    var anchor = new google.maps.MVCObject();
    anchor.set("position", e.latLng);

    if( e.feature.getProperty('AREA') ){
      var str = [];
      str.push('<div class="map-box"><strong>'+ e.feature.getProperty('PTNAME') + '</strong></div>');
      str.push('<div class="map-box">面積約: '+ e.feature.getProperty('turf_area')/(1000*1000) + ' 平方公里</div>');

      infoWindow.setContent(str.join(''));
      infoWindow.open(map, anchor);
    }else{
      infoWindow.close();
    }

  });

}

</script>


</body>
</html>